<template>
  <div id="register2">
    <van-password-input
        :value="code"
        info="验证码为 4 位数字"
        :focused="showKeyboard"
        :length="4"
        :mask="false"
        :error-info="errorInfo"
        @focus="showKeyboard = true"
        id="input"
    />
    <van-number-keyboard
        v-model="code"
        :show="showKeyboard"
        :maxlength="4"
        @blur="showKeyboard = false"
        z-index="100"
    />
    <div>
      <van-button @click="submit" plain :loading="isLoading" id="submitBtn" type="info" native-type="submit">
        提交
      </van-button>
    </div>
  </div>
</template>

<script>

import {Toast, PasswordInput, NumberKeyboard} from 'vant';

export default {
  name: "Register2",
  data() {
    return {
      code: '',
      showKeyboard: false,
      errorInfo: '',
      isLoading: false
    }
  },
  created() {
    this.checkStep();
  },
  methods: {
    checkStep() {
      if (!this.$store.state.registerInfo.info) {
        let errorPage = _g.showToast('fail','信息提交失败\n请重新填写信息');
        setTimeout(() => {
          errorPage.clear();
          this.$router.push('/register/1');
        }, 3000);
      }
    },
    submit() {
      let data = this.$store.state.registerInfo;
      this.isLoading = true;
      new Promise((resolve, reject) => {
        return axios.post('/yibancircle/saveMessage', {
          email: data.info.email,
          password: data.info.password,
          userName: data.info.username,
          userNick: data.info.username,
          sex: data.info.sex,
          schoolName: data.info.schoolName
        }).then(res => {
          if (res.status === 200) {
            resolve(res);
          } else {
            reject(res)
          }
        }).catch(err => reject(err))
      }).then(res => {
        Toast.success('注册成功！\n返回登陆页面');
        setTimeout(() => {
          this.$router.replace('/login');
        }, 1000);
      }).catch(res => {
        Toast.fail(res.msg + '\n请重新注册');
        setTimeout(() => {
          this.$router.push('/register');
        }, 1000);
      })
    },
    checkCode() {
      let c = JSON.parse(localStorage.getItem('forgetPwdCode'));
      if (c == this.code) {
        this.submit();
      } else {
        this.errorInfo = '验证码错误'
      }
    }
  },
  watch: {
    code(val) {
      if (val.length === 4) {
        this.checkCode();
      } else {
        this.errorInfo = '';
      }
    }
  }
}
</script>

<style scoped>
#submitBtn {
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 99;
}
</style>
